import axios from "axios";
import {ElMessage,ElMessageBox,ElNotification} from 'element-plus'
import router from "@/router";

// 请求拦截器
axios.interceptors.request.use(config => {
    // 如果存在token，则后续请求携带此token
    if (window.sessionStorage.getItem('tokenStr')) {
        config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr');
    }
    return config;
}, error => {
    console.log(error);
})


// 响应拦截器
axios.interceptors.response.use(success => {
    // 业务逻辑错误
    // 状态码为200表示请求成功
    if (success.status && success.status === 200) {
        // 这里对服务器端定义的错误进行拦截，打印服务器返回的错误信息
        if (success.data.code === 500 || success.data.code === 401 || success.data.code === 403) {
            ElMessage({message: success.data.message, type: 'error', center: true});
            return;
        }
        // 这里表示请求成功后，服务器也成功响应，如果有返回信息，则打印成功的信息
        // if (success.data.message) {
        //     ElMessage({message: success.data.message, type: 'success', center: true});
        // }
        return success.data;
    }
}, error => {
    if(error.response.status === 500){
        if(error.response.data && error.response.data.message){
          ElMessage({message: error.response.data.message, type: 'error', center: true});
        }
    }
    else if (error.response.status === 504 || error.response.status === 404) {
        ElMessage({message: '服务器好像坏掉了，待会再试试吧 (～￣▽￣)～', type: 'error', center: true});
    } else if (error.response.status === 403) {
        ElMessage({message: '权限不足，请联系管理员', type: 'error', center: true});
    } else if (error.response.status === 401) {
        ElMessage({message: '尚未登录，请登录再试', type: 'error', center: true});
        router.replace('/login').then(() => 'to login');
    } else {
      
        if (error.response.message) {

            ElMessage({message: error.response.message, type: 'error', center: true});
        }else if (error.response.msg) {
          ElMessage({message: error.response.msg, type: 'error', center: true});
      } else {
            ElMessage({message: '出现未知错误，请联系管理员!', type: 'error', center: true});
        }
    }
});

const baseUrl = '/api';
// 传送JSON格式的POST请求
export const postRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.post(`${baseUrl}${url}`, params).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err)
        })
    })
}
// GET请求
export const getRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.get(`${baseUrl}${url}`, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// 传送json格式的put请求
export const putRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.put(`${baseUrl}${url}`, params).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    })
}

// delete请求
export const deleteRequest = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.delete(`${baseUrl}${url}`, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

//=============================数据操作===============================

export const useHandlerEdit = (state) => {

    const handleEdit=(index,row)=>{
      state.editDialogVisible=true ;
      state.id = row.id ;
    }

    return {handleEdit}
  }

  export const useHandlerDetail = (state) => {

    const handleDetail=(index,row)=>{
      state.detailDialogVisible=true ;
      state.id = row.id ;
    }
    return {handleDetail}
  }



  export const useHandleSizeChange = (state,url)=>{
    const handleSizeChange=(newSize)=>{
      state.pageSize = newSize ;
      loadData(state,url);
    }
    return {
      handleSizeChange 
    }
 }
 export const  useHandleCurrentChange = (state,url)=>{
   const handleCurrentChange=(newPage)=>{
      state.pageNo = newPage ;
      state.currentPage = newPage ;
      loadData(state,url);
    }
    return {
      handleCurrentChange 
    }
 }

 export const  useHandlerSearch=(state,url)=>{
    const handlerSearch=()=>{
      state.currentPage=1 ;
      loadData(state,url) ;
  
    }
    return {handlerSearch} ;
  }

  export const useDelete = (state,url)=>{
    const handleDelete = (index,row)=>{
      ElMessageBox.confirm("你确定要删除吗","提示",{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning',
        callback:(action)=>{
          if('confirm'===action){
                    deleteRequest(url,{id:row.id}).then(
                      response=>{
                        if(response.code==200){
                          loadData(state,url)
                          ElNotification({
                          type:'success',
                          title:'成功',
                          message:"删除成功",
                          duration:2000
                          });
                        }
                      },error=>{
                        ElNotification({
                        type:"error",
                        title:'失败',
                        message:"删除失败",
                        duration:2000
                      });
  
                  }
                );
          }
         }
      })
    }
    return {handleDelete}
  }
  export const loadData = (state,url) => {

    var params={
      page:state.currentPage,
      limit:state.pageSize,
      keywords:state.searchContent
    }
      getRequest(url,params).then(response => {
          if (response) {
           state.tableData = response.page.list;
           state.total = response.page.totalCount ;
          }
        })
  }  

  // 判断内容是否含有表情字符，现有数据库不支持。
export const hasEmoji =(str = '') =>{
  const reg = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;
  return str.match(reg) && str.match(reg).length
}

export const  formatNowDate =()=>{
  Date.prototype.format = function(fmt)   
  { //author: meizz   
    var o = {   
      "M+" : this.getMonth()+1,                 //月份   
      "d+" : this.getDate(),                    //日   
      "h+" : this.getHours(),                   //小时   
      "m+" : this.getMinutes(),                 //分   
      "s+" : this.getSeconds(),                 //秒   
      "q+" : Math.floor((this.getMonth()+3)/3), //季度   
      "S"  : this.getMilliseconds()             //毫秒   
    };   
    if(/(y+)/.test(fmt))   
      fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
    for(var k in o)   
      if(new RegExp("("+ k +")").test(fmt))   
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
    return fmt;   
  }
  return new Date().format("yyyy-MM-dd") ;
  }

  export const  formatNowTime =()=>{
    Date.prototype.format = function(fmt)   
    { //author: meizz   
      var o = {   
        "M+" : this.getMonth()+1,                 //月份   
        "d+" : this.getDate(),                    //日   
        "h+" : this.getHours(),                   //小时   
        "m+" : this.getMinutes(),                 //分   
        "s+" : this.getSeconds(),                 //秒   
        "q+" : Math.floor((this.getMonth()+3)/3), //季度   
        "S"  : this.getMilliseconds()             //毫秒   
      };   
      if(/(y+)/.test(fmt))   
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
      for(var k in o)   
        if(new RegExp("("+ k +")").test(fmt))   
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
      return fmt;   
    }
    return new Date().format("yyyy-MM-dd hh:mm:ss") ;
    }

    export const getDateRegion = (beginDate,endDate)=>{
      if(beginDate != '' && endDate != ''){
         var aDate, oDate1, oDate2, iDays;
         if(beginDate.length==8){
            beginDate = beginDate.substr(0,4)+'-'+beginDate.substr(4,2)+'-'+beginDate.substr(6,2);
         }
         if(endDate.length==8){
            endDate = endDate.substr(0,4)+'-'+endDate.substr(4,2)+'-'+endDate.substr(6,2);
         }
         aDate = beginDate.split("-");
         oDate1 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]);   //转换为12/13/2008格式
         aDate = endDate.split("-");
         oDate2 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]);
         var i=(oDate1 - oDate2) / 1000 / 60 / 60 /24;
         /*if(i<0){
            i-=1;
         }else{
            i+=1;
         }*/
         iDays = i;   //把相差的毫秒数转换为天数
         return iDays; 
      }else{
         return 0;
      }
   };
   
 